package dominion.model.actions.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import dominion.model.Card;
import dominion.model.GameBoard;
import dominion.model.Player;
import dominion.model.actions.Action;
import dominion.utils.Constants;

public class Remodel extends Action {

	public Remodel() {
		this.cost = 4;
	}

	@Override
	public Card clone() {
		return new Remodel();
	}

	@Override
	public String toString() {
		return Constants.REMODEL;
	}

	@Override
	public String getDescription() {
		StringBuffer sb = new StringBuffer();
		sb.append(super.getDescription());
		sb.append("Trash a card from your hand.\n");
		sb.append("Gain a card costing $2 more than that card.\n");
		return sb.toString();
	}

	@Override
	public void doAction(Player player, GameBoard board, List<Player> players) throws IOException {
		if (player.getHand().size() == 1)
		{
			Constants.printer.print("Not enough cards in hand!");
			return;
		}
		playedCard(player);
		player.changeAction(-1);
		Constants.printer.print("Which card would you like to discard?");
		Constants.printer.print(player.printHand());

		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String input = null;
		boolean done = false;
		int highestCost = 0;
		while (!done && !player.getHand().isEmpty())
		{
			input = in.readLine().trim();
			if (player.getHand().contains(input))
			{
				Card card = player.getHand().getCard(input);
				card = player.drawFromDeck(card.toString(), Constants.HAND);
				highestCost = card.getCost() + 2;
				board.addToTrash(card);
				done = true;
			}
			else
			{
				Constants.printer.print("Card does not exist in hand.");
			}
		}

		done = false;
		Constants.printer.print("Pick a new card to buy, costing at most: " + highestCost);
		Constants.printer.printBoard(board);
		while (!done)
		{
			input = in.readLine().trim().toLowerCase();
			Card cardChoice = Constants.cardMap.get(input);
			if (cardChoice == null)
			{
				Constants.printer.print("Invalid selection");
			}
			else if (cardChoice.getCost() > highestCost)
			{
				Constants.printer.print(cardChoice.toString() + " is too expensive. Pick something that costs "
						+ highestCost + " or less.");
			}
			else
			{
				Card card = board.drawFromPile(cardChoice.toString());
				player.addToDeck(card, Constants.DISCARD_DECK);
				done = true;
			}
		}
	}
}
